<?php

namespace app\common\controller;

use think\cache\driver\Redis;
use think\Controller;
use think\Db;

/**
 * 公共资源-邮箱发送 验证
 */
class Email extends Controller
{
    public $redis = '';
    public function initialize(){

        $this->redis = new Redis(getRedisConfig());
    }
    /**
     * 发送验证码
     *  $email str 邮箱号
     *  $code str 验证码
     * @return 数据信息| 0 成功 !=0失败
     * @since 2023/08/04
     * @author ZhangXuanNeng
     */
    public function sendSms($email,$code){
        $str = '您的验证码是'.$code.'。如非本人操作，请忽略本邮件';
        $title = '邮箱登录';
        $name = '亲爱的玩家';
        $res = $this->sendMail($email,$title,$str,$name);
        if($res){
            $this->redis->set($email,$code,300);
            return ['code'=>0,'msg'=>'发送成功'];
        }else{
            return ['code'=>4014456,'msg'=>'发送失败'];
        }
    }
    /**
     * 邮件发送
     */
    public function sendMail($to, $title, $content,$name) {
        require_once VENDOR_PATH . 'PHPMailer/PHPMailerAutoload.php';
        $mail = new \PHPMailer();
        $mail->IsSMTP(); // 启用SMTP
        $mail->Host = config('email.MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->Port=80; //端口
        $mail->SMTPAuth = config('email.MAIL_SMTPAUTH'); //启用smtp认证
        $mail->Username = config('email.MAIL_USERNAME'); //你的邮箱名
        $mail->Password = config('email.MAIL_PASSWORD') ; //邮箱密码
        $mail->From = config('email.MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
        $mail->FromName = config('email.MAIL_FROMNAME'); //发件人姓名
        $mail->AddAddress($to,$name);
        $mail->WordWrap = 50; //设置每行字符长度
        $mail->IsHTML(config('email.MAIL_ISHTML')); // 是否HTML格式邮件
        $mail->CharSet = config('email.MAIL_CHARSET'); //设置邮件编码
        $mail->Subject =$title; //邮件主题
        $mail->Body = $content; //邮件内容
        $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
        return($mail->Send());
    }
    /**
     * 验证码验证
     * @param str $email 邮箱号
     * @param str $code 验证码
     * @return 数据信息|0 成功 !0失败
     * @since 2024/11/21
     * @author ZhangXuanNeng
     */
    public function smsVerify($email,$code){
        $res = $this->redis->get($email);
        if(empty($res)){
            return ['code'=>-1,'msg'=>'验证码已过期！请重新获取'];
        }
        if($res != $code){
            $num = $this->redis->get($email.'_num');
            $this->redis->set($email.'_num',$num + 1,60);
            if($this->redis->get($email.'_num') >= 3){
                $this->redis->rm($email.'_num');
                $this->redis->rm($email);
            }
            return ['code'=>-1,'msg'=>'输入验证码不正确'];
        }
        $this->redis->rm($email.'_num');
        $this->redis->rm($email);
        return ['code'=>0,'msg'=>'验证通过'];
    }
}
